﻿define(["moment", "module/moduleA/program/B01/custom_layout/default-config.js", 'xlsx'], function (moment) {
    return ["$scope", "$filter", "$stateParams", "config", "MMWService", "$calculater", "$mdDialog", "$state", '$log', '$interval',
    function ($scope, $filter, $stateParams, config, $MMWService, $calculater, $mdDialog, $state, $log, $interval,) {
        var timerSearch = null;
        $scope.init = function () {
            $scope.wo_no = '';
            $scope.mode = 'init';
            $scope.columnInfo = { name: $filter('translate')('SLI01.selectColumns.EQUIPMENTNO'), code: 'A.EQUIPMENTNO' };
            $scope.typeInfo = { name: $filter('translate')('common.report.condition.equal'), code: '0' };
            $scope.columnValue = '';
            $scope.conditionList = [];
            $scope.andonDataList = [];
            $scope.andonDataList_temp = [];
            $scope.andonDetailDataList = [];
            $scope.$on('$destroy',function(){
                $interval.cancel(timerSearch);
            })
            $scope.codeList = [
                { name: $filter('translate')('SLI01.selectColumns.BASEAREANO'), code: 'A.BASEAREANO' },
                { name: $filter('translate')('SLI01.selectColumns.AREANO'), code: 'A.AREANO' },
                { name: $filter('translate')('SLI01.selectColumns.EQUIPMENTTYPE'), code: 'A.EQUIPMENTTYPE' },
                { name: $filter('translate')('SLI01.selectColumns.EQUIPMENTNO'), code: 'A.EQUIPMENTNO' }
            ];
            $scope.modeList = [
                { name: $filter('translate')('common.report.condition.equal'), code: '0' },
                { name: $filter('translate')('common.report.condition.nequal'), code: '1' },
                { name: $filter('translate')('common.report.condition.contain'), code: '2' },
                { name: $filter('translate')('common.report.condition.ncontain'), code: '3' },
                { name: $filter('translate')('common.report.condition.exceed-equal'), code: '4' },
                { name: $filter('translate')('common.report.condition.less-equal'), code: '5' },
                { name: $filter('translate')('common.report.condition.exceed'), code: '6' },
                { name: $filter('translate')('common.report.condition.less'), code: '7' }
            ];
            $scope.refresh = {
                condition:[],
                count: 0,
                time: 30,
                page_time: 30,
                is_start: 'N',
                page_count:25,
                line_height:32,
                font_size:14
            };
        };

        $scope.setting = function(){
            $mdDialog.serviceDialog('C12Settings',
            angular.extend({}, $scope.refresh),
            function(refresh){
                $scope.refresh.time = refresh.time;
                $scope.refresh.page_time = parseInt(refresh.page_time);
                $scope.refresh.is_start = refresh.is_start;
                $scope.refresh.font_size = parseInt(refresh.font_size);
                $interval.cancel(timerSearch);
                timerSearch = null;
                $scope.search();
            });
        };

        // 设定查询字段
        $scope.loadCodeList = function () {
            LoadCodeList();
        };


        // 打开查询字段下拉选择
        function LoadCodeList() {
            $scope.$root.showSelect({
                title: $filter('translate')('common.report.condition_fields'),
                label: 'name',
                code: 'code',
                selectCode: '',
                list: $scope.codeList,
                confirm: function (selectItem, dialog) {
                    $scope.columnInfo.name = selectItem.name;
                    $scope.columnInfo.code = selectItem.code;
                    dialog.hide();
                }
            });
        };

        // 设定条件类型
        $scope.loadTypeList = function (item) {
            loadTypeList();
        };

        // 打开条件类型下拉选择
        function loadTypeList() {
            $scope.$root.showSelect({
                title: $filter('translate')('common.condition_title'),
                label: 'name',
                code: 'code',
                selectCode: $scope.columnInfo.code,
                list: $scope.modeList,
                confirm: function (selectItem, dialog) {
                    $scope.typeInfo.name = selectItem.name;
                    $scope.typeInfo.code = selectItem.code;
                    dialog.hide();
                }
            });
        };

        // 添加查询条件
        $scope.addCondition = function (type) {
            if ($scope.columnInfo.name != null && $scope.columnInfo.name != '' && $scope.columnValue != null && $scope.columnValue != '') {
                let conditionItem = {
                    columnName: $scope.columnInfo.name,
                    columnCode: $scope.columnInfo.code,
                    columnValue: ($scope.typeInfo.code != '2' && $scope.typeInfo.code != '3') ? $scope.columnValue : '%' + $scope.columnValue + '%',
                    conditionName: $scope.typeInfo.name,
                    conditionCode: $scope.typeInfo.code,
                    desc: $scope.columnInfo.name + ' ' + $scope.typeInfo.name + ' ' + $scope.columnValue
                }
                $scope.conditionList.push(conditionItem);
                $scope.columnValue = '';
            } 
            else {
                 // 20210127 add FOR #78814
                if(type == 0){
                    $scope.$root.showAlert($filter('translate')('C00.msg.condition_empty'));
                }
            }
        };

        // 点击查询条件
        $scope.selectCondition = function (index, item) {
            $log.log("==>点击查询条件");
            $scope.conditionList.splice(index, 1);
        };

        // 移除查询条件
        $scope.removeCondition = function (event, index) {
            $log.log("==>点击移除查询条件");
            $scope.conditionList.splice(index, 1);
            if($scope.conditionList.length == 0){
                $scope.columnInfo = { name: $filter('translate')('SLI01.selectColumns.EQUIPMENTNO'), code: 'A.EQUIPMENTNO' };
                $scope.isClose = false;
            }
        };

        // 搜索
        $scope.search = function () {
            search();
            if($scope.refresh.is_start == 'Y'){
                if (timerSearch == null) {
                    timerSearch = $interval(function () {
                        search();
                    }, Number($scope.refresh.time)*1000);
                } else {
                    $interval.cancel(timerSearch);
                    timerSearch = null;
                    timerSearch = $interval(function () { 
                        search();
                    }, Number($scope.refresh.time)*1000);
                }
            }
        };

        function search() {
            $scope.andonDataList = [];
            $scope.andonDataList_temp = [];
            let content = {
                conditionList: []
            };
            // 20210127 add FOR #78814
            $scope.addCondition(1);
            if ($scope.conditionList.length > 0) {
                let conditionList_temp = [];
                $scope.conditionList.forEach(function (item, index, array) {
                    let conditionItem = {
                        column_name: item.columnCode, // 列名
                        merge_condition_model: "AND", // 查询条件方式
                        query_mode: item.conditionCode, // 查詢條件代號	
                        value: item.columnValue,
                    };
                    conditionList_temp.push(conditionItem);
                })
                content.conditionList = conditionList_temp;
                $scope.isClose = true;
                getInfo(content);
            }else{
                if(timerSearch == null){
                    if($scope.conditionList.length == 0 && $scope.andonDataList.length == 0) {
                        $scope.$root.showConfirm($filter('translate')('common.msg.no_report_condition_confirm'), 
                        function(dialog){
                            dialog.hide();
                            getInfo(content);
                        });
                    }
                }else{
                    getInfo(content);
                }
            }         
        }

        function getInfo(content) {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SLI.slight_status_list_get',
                content: content,
                success: function (data) {
                    $scope.andonDataList = data.slightStatusList;
                    $scope.andonDataList_temp = data.slightStatusList;
                }
            });
        }

        // 获取安灯详情列表
        function getAndonDetailInfo () {
            $scope.andonDetailDataList = [];
            let content = {
                ID: ''
            }
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SLI.slight_detail_info_get',
                content: content,
                success: function (data) {
                    $scope.andonDetailDataList = data.slightDetailInfo;
                }
            });
        }

        // 汇出按钮（前端导出）
        $scope.export = function () {
            console.log("========汇出（导出）数据========")
            let listData = [];
            let detailListData = [];
            if (!$scope.andonDataList) {
                $scope.$root.showAlert($filter('translate')('SLI01.msg.no_data'));
                return;
            }
            let colorMap = {
                '#68BD84': $filter('translate')('SLI01.color_list.green'), // 绿色
                '#FFA500': $filter('translate')('SLI01.color_list.yellow'), // 黄色
                '#db4d3e': $filter('translate')('SLI01.color_list.red')// 红色
            }
           var list_temp = $scope.andonDataList_temp;
            for (var i = 0; i < list_temp.length; i++) {
                let itemData = list_temp[i];
                itemData.EquipmentColourStr = colorMap[itemData.EquipmentColour];
                itemData.QualityColourStr = colorMap[itemData.QualityColour];
                itemData.MaterialColourStr = colorMap[itemData.MaterialColour];
                itemData.ProdColourStr = colorMap[itemData.ProdColour];
                let list = {
                    设备编号: "",
                    设备类别: "",
                    设备名称: "",
                    基底区域编号: "",
                    区域编号: "",
                    安灯状态: "",
                    机台: "",
                    机台现况: "",
                    机台安灯颜色: "",
                    质量: "",
                    质量机台现况: "",
                    质量安灯颜色: "",
                    物料: "",
                    物料机台现况: "",
                    物料安灯颜色: "",
                    生产: "",
                    生产机台现况: "",
                    生产安灯颜色: ""
                };
                list.设备编号 = itemData.EQUIPMENTNO;
                list.设备类别 = itemData.EQUIPMENTTYPE;
                list.设备名称 = itemData.EquipmentName;
                list.基底区域编号 = itemData.BASEAREANO;
                list.区域编号 = itemData.AREANO;
                list.安灯状态 = itemData.SLightState;
                list.机台 = itemData.SLEquipment;
                list.机台现况 = itemData.SLEquipmentId;
                list.机台安灯颜色 = itemData.EquipmentColourStr;
                list.质量 = itemData.SLQuality;
                list.质量机台现况 = itemData.SLQualityId;
                list.质量安灯颜色 = itemData.QualityColourStr;
                list.物料 = itemData.SLMaterial;
                list.物料机台现况 = itemData.SLMaterialId;
                list.物料安灯颜色 = itemData.MaterialColourStr;
                list.生产 = itemData.SLProd;
                list.生产机台现况 = itemData.SLProdId;
                list.生产安灯颜色 = itemData.ProdColourStr;
                listData.push(list);
            }

            let andonDetailDataList_temp = $scope.andonDetailDataList;
            if (andonDetailDataList_temp.length > 0) {
                for (var i = 0; i < andonDetailDataList_temp.length; i++) {
                    let itemData = andonDetailDataList_temp[i];
                    let list = {
                        编号: "",
                        安灯类型编号: "",
                        设备编号: "",
                        区域编号: "",
                        生产批号: "",
                        作业站编号: "",
                        安灯原因: "",
                        紧急程度: "",
                        物料编号: "",
                        链结对象: "",
                        安灯现况: "",
                        响应等级: "",
                        安灯时间: "",
                        安灯用户: "",
                        接受时间: "",
                        接受用户: "",
                        开始时间: "",
                        开始用户: "",
                        完成时间: "",
                        完成用户: "",
                        提交时间: "",
                        提交用户: "",
                        描述: ""
                    };
                    list.编号 = itemData.ID;
                    list.安灯类型编号 = itemData.SLightTypeNo;
                    list.设备编号 = itemData.EquipmentNo;
                    list.区域编号 = itemData.AreaNo;
                    list.生产批号 = itemData.LotNo;
                    list.作业站编号 = itemData.OPNo;
                    list.安灯原因 = itemData.SLightReasonNo;
                    list.紧急程度 = itemData.Grade;
                    list.物料编号 = itemData.MaterialNo;
                    list.链结对象 = itemData.Measure;
                    list.安灯现况 = itemData.SLightState;
                    list.响应等级 = itemData.ResponseLevel;
                    list.安灯时间 = itemData.AndonTime;
                    list.安灯用户 = itemData.Andoner;
                    list.接受时间 = itemData.ReceiveTime;
                    list.接受用户 = itemData.Receiver;
                    list.开始时间 = itemData.StartTime;
                    list.开始用户 = itemData.Starter;
                    list.完成时间 = itemData.FinishTime;
                    list.完成用户 = itemData.Finisher;
                    list.提交时间 = itemData.ConfromTime;
                    list.提交用户 = itemData.Confromer;
                    list.描述 = itemData.Description;
                    detailListData.push(list);
                }
            }
            if (listData.length != 0) {
                /* generate a worksheet */
                let list_ws = XLSX.utils.json_to_sheet(listData);
                /* add to workbook */
                let wb = XLSX.utils.book_new();
                XLSX.utils.book_append_sheet(wb, list_ws, $filter('translate')('SLI01.excel_sheet_names.name0'));
                if (detailListData.length > 0) {
                    let detail_list_ws = XLSX.utils.json_to_sheet(detailListData);
                    XLSX.utils.book_append_sheet(wb, detail_list_ws, $filter('translate')('SLI01.excel_sheet_names.name1'));
                }
                /* write workbook and force a download */
                var timestamp = $scope.formatDate(new Date());
                var tittle = $filter('translate')('SLI01.excel_names.name0') + timestamp + ".xlsx";
                const xlsxDataStr =  XLSX.writeFile(wb, tittle)
                console.log(xlsxDataStr)
                if(xlsxDataStr.length > 0){
                    $scope.$root.showToast($filter('translate')('SLI03.msg.print_success'));
                }
            }
            else {
                $scope.$root.showAlert($filter('translate')('SLI01.msg.no_data'));

            }
        };

        $scope.formatDate = function (date) {
            let year = date.getFullYear();
            let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
            let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
            let hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
            let minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
            let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            return year  + month  + day +  hours  + minutes + seconds;	// 返回格式化后的日期
        };

        // 打开安灯信息详细页面
        $scope.toAndonDetail = function (id) {
            console.log("==>toAndonDetail:" + id);
            $mdDialog.serviceDialog('AndonDetailService', {
                id: id,
                callback: function () {
                    dialog.beforeShown();
                }
            });
        }

        $scope.back = function () {
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        };

        // 取消
        $scope.cancel = function () {
            $scope.mode = 'init';
            document.getElementById('kmi-pdf-panel').src = '';
            $scope.printList = [];
        };

    }
    ];
});
